<?php
class cmsdream_load extends cmsdream_main {

	public function __construct($db) {
		/*
		$saveHandler = new cmsdream_session($db);
		session_set_save_handler(
				array($saveHandler, 'open'), 
				array($saveHandler, 'close'), 
				array($saveHandler, 'read'), 
				array($saveHandler, 'write'), 
				array($saveHandler, 'destroy'), 
				array($saveHandler, 'gc')
		);
		*/
		session_start();
		$this->config = $GLOBALS["C"];
		$this->db = $db;
		$this->query = new cmsdream_query();
		$this->cache = new cmsdream_data();
		$this->initialize_setting(); 
		$this->initialize_request();
		$this->initialize_milieu();
		$this->initialize_logged_user();
		$this->initialize_template();
	}	
	
	private function initialize_milieu() {
		$len1 = strlen($this->setting->siteurl);
		$len2 = strlen($this->config->SITEPATH);
		$this->hash = md5(substr($this->setting->siteurl, 0, ($len1 - $len2)));
		unset($len1,$len2);
				
		$this->query_vars = $this->query->parse_query_vars($this->public_query_vars, $this->query_vars, $this->hash);
		//set a default value;		
		$this->query->client = ($this->query->is_wap && $this->query->client=='web') ? $this->config->WAP_CLIENT : $this->query->client;
		$this->template = $this->query->get_template_name();
		
		if(!isset($GLOBALS['DB'])) $GLOBALS['DB'] = $this->db;
		if(!isset($GLOBALS['S'])) $GLOBALS['S'] = $this->setting;
		if(!isset($GLOBALS['V'])) $GLOBALS['V'] = $this->query_vars;
		if(!isset($GLOBALS['E'])) $GLOBALS['E'] = $this->cache;
		if(!isset($GLOBALS['Q'])) $GLOBALS['Q'] = $this->query;
				
		if($this->query->is_feed) {
			$header = 'text/xml';
		} else {		
			$header = ($this->query->is_wap && $this->query->client == 'wap') ? 'text/vnd.wap.wml' : 'text/html';
		}
		header("Content-Type:$header; charset=utf-8");
	}
	
	private function initialize_template() {
		if(in_array($this->template, array('index', 'category', 'tag', 'search', 'author'))) {
			$this->template = 'index';
		}
		if($this->query->is_page){
			$pn = $this->get_page_params();
			if(in_array($pn, $this->permanent_page_name)) {
				$this->template = $pn;
			}
		}
		
		if(!$this->query->is_feed && strpos($this->template,'boot')===false) {
			$s = new cmsdream_statistics();
			$s->save();
			unset($s);
		}
		
		if(file_exists("./modules/module.{$this->template}.php")) {
			require_once("./modules/module.{$this->template}.php");
		}
		
		$temp = ($this->query->is_wap) ? $this->query->client : $this->setting->template;		
		$temp = $this->config->TEMPLATEDIR."/".$temp."/";
		@chdir($temp);
		if(!file_exists($temp.$this->template.".php")) {
			echo("File " . $temp . $this->template . ".php is not existing.");
			exit;
		}
		include($temp.$this->template.".php");
	}
	
	private function initialize_request() {
		/*
		$home_path = parse_url($this->setting->home);
		if(strtolower($_SERVER['HTTP_HOST']) != $home_path['host']) {
			//$uri = mb_convert_encoding($_SERVER['REQUEST_URI'], 'utf-8', 'GBK');
			$uri = urldecode($_SERVER['REQUEST_URI']);
			header("location:http://".$home_path['host'].str_replace('/index.php','',$uri));
			exit;
		}
		*/
		
		if(isset($this->setting->rewrite_rules)) {
			$rewrite = $this->setting->rewrite_rules;
			if ( ! empty($rewrite) ) {	
				if ( isset($_SERVER['PATH_INFO']) )
					//$pathinfo = mb_convert_encoding($_SERVER['PATH_INFO'], 'utf-8', 'GBK');
					$pathinfo = urldecode($_SERVER['PATH_INFO']);
				else
					$pathinfo = '';
				$pathinfo_array = explode('?', $pathinfo);
				$pathinfo = str_replace("%", "%25", $pathinfo_array[0]);
				//$req_uri = mb_convert_encoding($_SERVER['REQUEST_URI'], 'utf-8', 'GBK');
				$req_uri = urldecode($_SERVER['REQUEST_URI']);
				$req_uri_array = explode('?', $req_uri);
				$req_uri = $req_uri_array[0];
				if(isset($req_uri_array[1]))
					$req_get = $this->parse_matched_query($req_uri_array[1]);
				$self = $_SERVER['PHP_SELF'];
				
				$home_path = parse_url($this->setting->home);
				if ( isset($home_path['path']) )
					$home_path = $home_path['path'];
				else
					$home_path = '';
				$home_path = trim($home_path, '/');

				$req_uri = str_replace($pathinfo, '', $req_uri);
				$req_uri = trim($req_uri, '/');
				$req_uri = preg_replace("|^$home_path|", '', $req_uri);
				$req_uri = trim($req_uri, '/');
				$pathinfo = trim($pathinfo, '/');
				$pathinfo = preg_replace("|^$home_path|", '', $pathinfo);
				$pathinfo = trim($pathinfo, '/');
				$self = trim($self, '/');
				$self = preg_replace("|^$home_path|", '', $self);
				$self = trim($self, '/');

				if ( ! empty($pathinfo) && !preg_match('|^.*index.php$|', $pathinfo) ) {
					$request = $pathinfo;
				} else {
					// If the request uri is the index, blank it out so that we don't try to match it against a rule.
					if ( $req_uri == 'index.php' )
						$req_uri = '';
					$request = $req_uri;
				}
				$this->request = $request_match = $request;
				
				foreach ( (array) $rewrite as $match => $query) {			
					if ( (! empty($req_uri)) && (strpos($match, $req_uri) === 0) && ($req_uri != $request) )
						$request_match = $req_uri . '/' . $request;

					if ( preg_match("#^$match#", $request_match, $matches) || preg_match("#^$match#", urldecode($request_match), $matches) ) {
						$query = preg_replace("!^.+\?!", '', $query);
						$query = $this->parse_matched_query($query);
						break;
					}
				}
				
				if(!empty($query) && is_array($query)) {
					foreach($query as $var => $value) {
						if(preg_match('/^\$matches\[([\d]+)\]$/', $value, $m))
						$this->query_vars[$var] = isset($matches[$m[1]]) ? $matches[$m[1]] : null;
					}
				}
				
				if(isset($req_get)) {
					foreach((array) $req_get as $var => $v) {
						if(!in_array($var, $this->public_query_vars)) $this->query_vars[$var] = $v;
					}
				}
			}
		}
		
		foreach ( $this->public_query_vars as $var ) {
			if ( isset( $_POST[$var] ) ) {
				$this->query_vars[$var] = $_POST[$var];
			} else if ( isset( $_GET[$var] ) )
				$this->query_vars[$var] = $_GET[$var];

			if ( !empty( $this->query_vars[$var] ) ) {
				if ( ! is_array( $this->query_vars[$var] ) ) {
					$this->query_vars[$var] = (string) $this->query_vars[$var];
				} else {
					foreach ( $this->query_vars[$var] as $vkey => $v ) {
						if ( !is_object( $v ) ) {
							$this->query_vars[$var][$vkey] = (string) $v;
						}
					}
				}
			}
		}
	}
	
	private function initialize_setting() {
		$this->setting = $this->cache->get("setting", true);
		if(!$this->setting) {
			$this->setting = new stdClass;
			foreach($this->db->fetch_all("SELECT option_name, option_value FROM {$this->config->TABLE_PREFIX}options WHERE autoload = 'yes'") as $name => $row) {
				if(!preg_match('/^(widget_|blog_user_|sidebars_|cron|_|zh_cn_|dashboard_widget_|theme_mods_|lw_|custom_community_theme_|wap_|dismissed_|pagelines_|category_children|current_theme|active_|dotb_|nav_menu_)/i', $row->option_name) &&
					!preg_match('/[\-]+/i', $row->option_name)) {
					if(preg_match('/^([a-z])\:([\d]+)\:\{(.*)\}$/i', $row->option_value) || preg_match('/^([a-z])\:([\d]+)\:"stdClass"\:([\d]+)\:\{(.*)\}$/i', $row->option_value)) {
						$this->setting->{$row->option_name} = unserialize($row->option_value);
					} else {
						$this->setting->{$row->option_name} = $row->option_value;
					}
				}
			}
			$this->setting->template = $this->config->THEMES;
			$this->setting->static = $this->config->STATIC_PATH;
			$this->setting->home = $this->setting->home . $this->config->SITEPATH;
			$this->setting->siteurl = $this->setting->siteurl . $this->config->SITEPATH;
			$this->cache->write("setting", str_replace("'", "\\'", serialize($this->setting)), time());
		}
	}
	
	private function parse_matched_query($str) {
		$return = array();
		$str = explode('&', $str);
		foreach ($str as $section) {
			if (strpos($section, '=') !== false) {
				list($name, $value) = explode('=', $section, 2);
				$return[urldecode($name)] = urldecode($value);
			} else {
				$return[urldecode($section)] = null;
			}
		}
		return $return;
	}
	
	private function initialize_logged_user(){
		$user = cmsdream_login::get_sc("wordpress_logged_in_".$this->hash);
		$user = explode('|', $user);
		$name = empty($user) ? '' : (isset($user[0]) ? $user[0] : '');
		$uid = ($name=='') ? 0 : $this->db->fetch_field("SELECT ID FROM {$this->config->TABLE_PREFIX}users WHERE user_nicename = '$name' LIMIT 1");
		$uid = $this->cache->get_author_detail($uid);
		if(empty($uid)){
			$this->logged_user = new stdClass();
			$this->logged_user->ID = 0;
		} else {
			$this->logged_user = $uid;
		}
	}
	
	public function __destruct(){
	
	}
	
}


